package com.aynu.webshop.web.controller;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.collections.ListUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.aynu.webshop.web.model.Category;
import com.aynu.webshop.web.model.Goods;
import com.aynu.webshop.web.model.Orderform;
import com.aynu.webshop.web.model.User;
import com.aynu.webshop.web.pagemodel.PageModel;
import com.aynu.webshop.web.service.CategoryService;
import com.aynu.webshop.web.service.GoodsService;
import com.aynu.webshop.web.util.FinalVarUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
@RequestMapping(value = "/goods")
public class GoodsController {
	@Resource
	private GoodsService goodsService;
	@Resource
	private CategoryService categoryService;
	/**
	 * 
	 * @param model
	 * @param request
	 * @return 
	 * 方法说明：获取所有商品信息
	 */
	@RequestMapping(value = "/getAllGoods", method = RequestMethod.GET)
	public ModelAndView getAllGoods(HttpServletRequest request)
			throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		ModelAndView mv = new ModelAndView();
		User user = (User) request.getSession().getAttribute("user");
		mv.addObject("user",user);
		PageModel pageModel = new PageModel();
		List<Goods> list = goodsService.selectList();
		String th_list = FinalVarUtil.GoodsTh;
		pageModel.setTh_list(th_list);
		List<Category> listParent = categoryService.selectListParent();
		for(Category parent : listParent) {
			List<Category> children = categoryService.selectListChild(parent.getCatId());
			parent.setChild(children);
		}
		mv.addObject("parents", listParent);
		mv.addObject("pageModel", pageModel);
		mv.addObject("list", list);
		mv.setViewName("goods/goodsList");
		return mv;
	}
	/**
	 * 
	 * @param model
	 * @param request
	 * @return 
	 * 方法说明：获取单个商品信息
	 */
	@RequestMapping(value = "/getGoodsById", method = RequestMethod.GET)
	public ModelAndView getGoodsById(HttpServletRequest request,Integer gid) {
		ModelAndView mv = new ModelAndView();
		Goods good = goodsService.selectById(gid);
		System.out.println(good);
		mv.addObject("good", good);
		mv.setViewName("goods/goodsDetail");
		return mv;
	}
	/**
	 * 
	 * @param model
	 * @param request
	 * @return 
	 * 方法说明：首页获取所有物品
	 */
	@RequestMapping(value = "/getGoodsList", method = RequestMethod.POST)
	public String getAllCategoryOne(HttpServletRequest request, HttpServletResponse response ,Integer tid) {
		JSONObject result = new JSONObject();
		List<Goods> list = goodsService.selectList();
		JSONArray json = JSONArray.fromObject(list); 
		result.put("json", json);
		response.setCharacterEncoding("UTF-8");  
        try {  
            response.getWriter().write(result.toString());  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
		return null;
	}
	
	/**
	 * 
	 * @param model
	 * @param request
	 * @return 
	 * 方法说明：更新商品状态
	 */
	@RequestMapping(value = "/updateStatus", method = RequestMethod.GET)
	public ModelAndView updateStatus(HttpServletRequest request,Integer gid,Integer status){
		ModelAndView mv = new ModelAndView("redirect:getAllGoods");
		Goods good = goodsService.selectById(gid);
		if(good.getgCount()!=0){
			good.setgStatus(status);
		}else{
			good.setgStatus(2);
		}
		goodsService.update(good);
		return mv;
	}
	
	/**
	 * 
	 * @param model
	 * @param request
	 * @return 
	 * 方法说明：删除商品
	 */
	@RequestMapping(value = "/deleteGoods", method = RequestMethod.GET)
	public ModelAndView deleteGoods(HttpServletRequest request,Integer gid){
		ModelAndView mv = new ModelAndView("redirect:getAllGoods");
		goodsService.delete(gid);
		return mv;
	}
	/**
	 * 
	 * @param model
	 * @param request
	 * @return 
	 * 方法说明：获取某分类下的所有商品
	 */
	@RequestMapping(value = "/getGoodsByCategory", method = RequestMethod.GET)
	public ModelAndView getGoodsByCategory(HttpServletRequest request,Integer catid){
		System.out.println(catid+"catid");
		ModelAndView mv = new ModelAndView();
		List<Category> listChild = categoryService.selectListChild(catid);//根据父id查询所有子id
		List<Goods> goods=new ArrayList<Goods>();
		List<Goods> good=null;
		for(int i=0;i<listChild.size();i++) {
			System.out.println(listChild.size()+"-----"+listChild.get(i).getCatId());
			good = goodsService.selectListByCatcid(listChild.get(i).getCatId());//根据子id查询所有商品
			goods.addAll(good);
			System.out.println("goodsList"+goods);
		}
		System.out.println("最终goodList"+goods);
		mv.addObject("goods", goods);
		mv.setViewName("goods/allGoods");
		return mv;
	}
	/**
	 * 
	 * @param model
	 * @param request
	 * @return 
	 * 方法说明：补货
	 */
	@RequestMapping(value = "/addCount", method = RequestMethod.POST)
	public ModelAndView addCount(HttpServletRequest request,Goods good,Integer addCount){
		ModelAndView mv = new ModelAndView("redirect:getAllGoods");
		if(good.getgCount()+addCount!=0){
			good.setgStatus(1);
		}else{
			good.setgStatus(2);
		}
		good.setgCount(good.getgCount()+addCount);
		goodsService.update(good);
		return mv;
	}
	/**
	 * 
	 * @param model
	 * @param request
	 * @return 
	 * 方法说明：添加商品
	 */
	@RequestMapping(value = "/addGoods", method = RequestMethod.POST)
	public ModelAndView addGoods(HttpServletRequest request,Goods good,HttpSession session,
			@RequestParam(value = "gPicture2", required = false) MultipartFile gPicture2) {
		ModelAndView mv = new ModelAndView("redirect:getAllGoods");
		if(gPicture2!=null){
			String path = session.getServletContext().getRealPath("goodsPicture/");
			String fileName = gPicture2.getOriginalFilename();
			if(!StringUtils.isEmpty(fileName)&&StringUtils.hasLength(fileName)){
				fileName =new Date().getTime()+""+fileName.substring(fileName.lastIndexOf("."));
				File targetFile = new File(path,fileName );
				if (!targetFile.exists()) {
					targetFile.mkdirs();
				}
				try {
					gPicture2.transferTo(targetFile);
				} catch (Exception e) {
					e.printStackTrace();
				}
				good.setgPicture("/picture/"+fileName);
			}else{
				good.setgPicture("/picture/small_201603211102144090.jpg");
			}
		}
		if(good.getgCount()!=0){
			good.setgStatus(1);
		}else{
			good.setgStatus(2);
		}
		if(goodsService.insert(good)!=1){
			//model.addAttribute("msg", "发布失败");
			System.out.println("发布失败");
			return mv;
		}
		System.out.println("发布成功！");
		return mv;
	}
	/**
	 * 
	 * @param model
	 * @param request
	 * @return 
	 * 方法说明：修改商品
	 */
	@RequestMapping(value = "/editGoods", method = RequestMethod.POST)
	public ModelAndView editGoods(HttpServletRequest request,Goods good,HttpSession session,
			@RequestParam(value = "gPicture3", required = false) MultipartFile gPicture3) {
		ModelAndView mv = new ModelAndView("redirect:getAllGoods");
		if(gPicture3!=null){
			String path = session.getServletContext().getRealPath("goodsPicture/");
			String fileName = gPicture3.getOriginalFilename();
			if(!StringUtils.isEmpty(fileName)&&StringUtils.hasLength(fileName)){
				fileName =new Date().getTime()+""+fileName.substring(fileName.lastIndexOf("."));
				File targetFile = new File(path,fileName );
				if (!targetFile.exists()) {
					targetFile.mkdirs();
				}
				try {
					gPicture3.transferTo(targetFile);
				} catch (Exception e) {
					e.printStackTrace();
				}
				good.setgPicture("/picture/"+fileName);
			}else{
				good.setgPicture("/picture/small_201603211102144090.jpg");
			}
		}
		if(good.getgCount()!=0){
			good.setgStatus(1);
		}else{
			good.setgStatus(2);
		}
		if(goodsService.update(good)!=1){
			//model.addAttribute("msg", "发布失败");
			System.out.println("更新失败");
			return mv;
		}
		System.out.println("更新成功！");
		return mv;
	}
	
	

}
